<template>
  <q-page class="q-pa-md">
    <div class="row items-center">
      <div class="q-pb-md text-h5">
        {{ pageTitle }}
        <span class="text-subtitle1">列表</span>
      </div>
      <q-space></q-space>
      <search-bar-toggle-btn v-model="searchBarVisibility"></search-bar-toggle-btn>
    </div>
    <!-- 查询菜单 -->
    <div class="q-pa-sm shadow-2 q-mb-md items-center" v-show="searchBarVisibility">
      <div class="row q-col-gutter-sm">
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">仓库</div>
          <div class="col-8">
            <simple-filter-select :options="$d.whDropdownList" :readonly="listDataLoadingState" :use-filter="false"
              option-label="whName" option-value="whId" v-model="fpsReq.whId" @update:model-value="onWhChanged" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">货主</div>
          <div class="col-8">
            <simple-filter-select :options="$d.storerDropdownList" option-label="abbrName" option-value="mfId"
              v-model="fpsReq.storerId" :auto-select-single-option="false" :readonly="listDataLoadingState" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">来源储区</div>
          <div class="col-8">
            <simple-filter-select v-model="fpsReq.fZoneId" :options="$d.zoneDropdownList" :use-filter="false"
              :auto-select-single-option="false" :readonly="listDataLoadingState" option-label="zoneName"
              option-value="zoneId" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">目的储区</div>
          <div class="col-8">
            <simple-filter-select v-model="fpsReq.tZoneId" :options="$d.zoneDropdownList" :use-filter="false"
              :auto-select-single-option="false" :readonly="listDataLoadingState" option-label="zoneName"
              option-value="zoneId" />
          </div>
        </div>
        <div v-if="$d.actualFieldShown.expectedDtBegin && fpsInfo.filtersInfo?.expectedDtBegin?.show"
          class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">计划移库日期从</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.expectedDtBegin" :error="v$.expectedDtBegin.$error"
              :error-message="e$(v$.expectedDtBegin.$errors)" :hide-bottom-space="true" :append-icon-show="true"
              :readonly="listDataLoadingState" clearble :use-date-picker="true">
            </easy-input>
          </div>
        </div>
        <div v-if="$d.actualFieldShown.expectedDtEnd && fpsInfo.filtersInfo?.expectedDtEnd?.show"
          class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">计划移库日期至</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.expectedDtEnd" :error="v$.expectedDtEnd.$error"
              :error-message="e$(v$.expectedDtEnd.$errors)" :hide-bottom-space="true" :append-icon-show="true"
              :readonly="listDataLoadingState" clearble :use-date-picker="true">
            </easy-input>
          </div>
        </div>
        <div v-if="$d.actualFieldShown.moveDtBegin && fpsInfo.filtersInfo?.moveDtBegin?.show"
          class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">实际移库日期从</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.moveDtBegin" :error="v$.moveDtBegin.$error"
              :error-message="e$(v$.moveDtBegin.$errors)" :hide-bottom-space="true" :append-icon-show="true"
              :readonly="listDataLoadingState" clearble :use-date-picker="true">
            </easy-input>
          </div>
        </div>
        <div v-if="$d.actualFieldShown.moveDtEnd && fpsInfo.filtersInfo?.moveDtEnd?.show"
          class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">实际移库日期至</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.moveDtEnd" :error="v$.moveDtEnd.$error"
              :error-message="e$(v$.moveDtEnd.$errors)" :hide-bottom-space="true" :append-icon-show="true"
              :readonly="listDataLoadingState" clearble :use-date-picker="true">
            </easy-input>
          </div>
        </div>
        <div v-if="$d.actualFieldShown.moveState && fpsInfo.filtersInfo?.moveState?.show"
          class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">状态</div>
          <div class="col-8">
            <simple-filter-select :options="$d.moveStateDropdownList" v-model="fpsReq.moveState"
              :use-filter="false" :readonly="listDataLoadingState" />
          </div>
        </div>
      </div>
      <div class="row q-pt-sm">
        <div class="q-mr-sm">
          <q-btn :disable="listDataLoadingState" @click="loadListData(2)" color="primary" icon="search" label="查询" />
        </div>
        <div>
          <filter-options-cfg v-model:option-list="fpsInfo.filtersInfo"
            @update-filter-options-for-save="fpsAssist.saveFilterOptions">
          </filter-options-cfg>
        </div>
      </div>
    </div>
    <div class="shadow-2">
      <q-table @request="fpsAssist.onDataTableRequest" :rows="$d.tableData" :columns="fpsInfo.columnsInfo"
        separator="cell" row-key="moveId" v-model:pagination="fpsInfo.paginationInfo" v-model:selected="$d.selectedItems"
        :visible-columns="fpsInfo.visibleColumns" dense flat :hide-pagination="true" :loading="listDataLoadingState"
        color="primary" binary-state-sort @row-dblclick="(evt,row)=>{fpsNav.gotoDetail(row.moveId)}" selection="multiple">
        <template v-slot:top="props">
          <!--功能按钮-->
          <div class="q-gutter-sm">
            <q-btn color="primary" icon="add" label="新建"
              @click="fpsNav.gotoCreate"
              v-if="fx.hasModifyRight('Wms.Inv.InvMove.Edit')" />
            <q-btn :disable="$d.selectedItems.length === 0" @click="deleteInvMoves" color="red" icon="delete_outline"
              label="批量删除" v-if="fx.hasModifyRight('Wms.Inv.InvMove.Edit')" />
<!--            <q-btn @click="onImportInvMovesByExcel" color="primary" icon="fas fa-file-import" label="贴标移库单导入"-->
<!--              v-if="fx.hasModifyRight('Wms.Inv.InvMove.Edit')" />-->
          </div>
          <!--填充所有剩余空间-->
          <q-space />
          <table-col-options-cfg v-model:visible-columns="fpsInfo.visibleColumns"
            v-model:table-columns="fpsInfo.columnsInfo" class="q-mx-sm"
            @update-col-options-for-save="fpsAssist.saveColOptions"></table-col-options-cfg>
          <q-btn :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'" :ripple="false"
            :title="props.inFullscreen ? '退出全屏' : '全屏显示'" dense flat @click="props.toggleFullscreen" />
        </template>
        <template v-slot:no-data>
          <span class="full-width text-center"> <q-icon name="error_outline" /> 无数据 </span>
        </template>
        <template v-slot:body-cell-operation="props">
          <q-td :props="props" auto-width>
            <q-btn v-if="fx.hasModifyRight('Wms.Inv.InvMove.Edit')"
              @click="evt=> fpsNav.gotoEdit(props.row.moveId, evt)" class="btn-in-row" color="primary" dense label="编辑"
            />
            <q-btn class="q-ml-xs btn-in-row" color="primary" dense label="查看"
              @click="evt=> fpsNav.gotoDetail(props.row.moveId, evt)" />
          </q-td>
        </template>
        <!--状态列插槽-->
        <template v-slot:body-cell-moveState="props">
          <q-td :props="props" auto-width>
            <q-badge :color="fx.fmt.fmtMoveStateColor(props.row.moveState)"
              :label="fx.fmt.fmtMoveState(props.row.moveState)" />
          </q-td>
        </template>
        <template v-slot:body-cell-docType="props">
          <q-td :props="props" auto-width>
            {{ fx.fmt.fmtInvMoveDocType(props.row.docType) }}
          </q-td>
        </template>
        <template v-slot:bottom>
          <paging-bar :loading-state="listDataLoadingState" :pageNo="fpsReq.pageNo" :pageSize="fpsReq.pageSize"
            :totalAmount="fpsInfo.totalAmount" @pagesize-changed="fpsAssist.onPageSizeChanged"
            @go-to-page="fpsNav.gotoPage" />
        </template>
      </q-table>
    </div>
    <!--批量导入-->
    <q-dialog transition-hide="none" transition-show="none" v-model="showingInvMoveImportDlg">
      <q-card style="max-width: 400px; width: 100%">
        <q-card-section class="q-pa-sm">
          <div class="text-h6">贴标移库单导入
            <a @click="fx.nw.downloadFile('/project/mhlbc/res/download/mhl-labeling-move-import-template.xlsx','',false)"
              class="text-body2" href="javascript:void(0)">导入模板下载</a></div>
        </q-card-section>
        <q-separator />
        <!--错误提示-->
        <q-banner class="text-white bg-red q-mt-sm q-mx-sm" dense inline-actions v-if="errorMessageForInvMoveImport">
          {{ errorMessageForInvMoveImport }}
          <template v-slot:action>
            <q-btn @click="errorMessageForInvMoveImport = ''" dense flat icon="close" size="sm" />
          </template>
        </q-banner>
        <div class="q-pa-sm">
          <div class="row justify-between">
            <input ref="asnListExcelFileInput" type="file" />
          </div>
        </div>
        <q-separator class="separator" />
        <q-card-actions align="right">
          <q-btn @click="importInvMoveListExcel" color="primary" label="确定" />
          <q-btn color="primary" label="取消" outline unelevated v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>
<script lang="ts">
export default {
  name: 'WmInvMoveListStd'
}
</script>
<script lang="ts" setup>
import {ColumnInfo, FilterInfo} from '@njt/foundation/defs/comm'
import {reactive, ref} from 'vue'
import {GetInvMoveListReq, GetInvMoveResp, WmInvMove} from '@njt/wms/defs/inventory/invmove.d'
import {useFpsHelper} from '@njt/foundation/hooks/fpsHelper'
import {useTitleHelper} from '@njt/foundation/hooks/titleHelper'
import {WmWhLite} from '@njt/wms/defs/basic/wh.d'
import {WmZoneLite} from '@njt/wms/defs/basic/zone.d'
import useVuelidate from '@vuelidate/core'
import {MfLite} from '@njt/foundation/helper/dropdownlist.d'
import _ from 'lodash'
// 是否处于数据列表加载的状态
let listDataLoadingState = ref(false)
const pageTitle = '移库单'
useTitleHelper(pageTitle)
$f.fmt.prepartMoveDocTypeFmt()
// 列参数
const columnsDefine: ColumnInfo[] = [
  {
    label: '操作',
    name: 'operation',
    field: 'operation',
    align: 'left',
    defOrder: 1,
    defVisible: true
  },
  {
    label: '移库单ID',
    name: 'moveId',
    field: 'moveId',
    align: 'left',
    defOrder: 2,
    sortable: true,
    defVisible: true
  },
  {
    label: '仓库ID',
    name: 'whId',
    field: 'whId',
    align: 'left',
    defOrder: 3,
    defVisible: false
  },
  {
    label: '仓库名称',
    name: 'whName',
    field: 'whName',
    align: 'left',
    defOrder: 4,
    sortable: true,
    defVisible: true
  },
  {
    label: '货主ID',
    name: 'storerId',
    field: 'storerId',
    align: 'left',
    defOrder: 5,
    defVisible: false
  },
  {
    label: '货主名称',
    name: 'storerAbbrName',
    field: 'storerAbbrName',
    align: 'left',
    defOrder: 6,
    sortable: true,
    defVisible: true
  },
  {
    label: '移库原因',
    name: 'reason',
    field: 'reason',
    align: 'left',
    defOrder: 7,
    defVisible: true
  },
  {
    label: '移库类型',
    name: 'docType',
    field: 'docType',
    align: 'left',
    defOrder: 8,
    defVisible: true
  },
  {
    label: '状态',
    name: 'moveState',
    field: 'moveState',
    align: 'left',
    defOrder: 9,
    sortable: true,
    defVisible: true
  },
  {
    label: '来源储区ID',
    name: 'fZoneId',
    field: 'fZoneId',
    align: 'left',
    defOrder: 10,
    defVisible: false
  },
  {
    label: '来源储区名称',
    name: 'fZoneName',
    field: 'fZoneName',
    align: 'left',
    defOrder: 11,
    sortable: true,
    defVisible: true
  },
  {
    label: '目的储区ID',
    name: 'tZoneId',
    field: 'tZoneId',
    align: 'left',
    defOrder: 12,
    defVisible: false
  },
  {
    label: '目的储区名称',
    name: 'tZoneName',
    field: 'tZoneName',
    align: 'left',
    defOrder: 13,
    sortable: true,
    defVisible: false
  },
  {
    label: '计划移库日期',
    name: 'expectedDt',
    field: 'expectedDt',
    align: 'left',
    defOrder: 14,
    sortable: true,
    defVisible: true,
    format: (value: string) => $f.fmt.dtFmtDateOnly(value)
  },
  {
    label: '实际移库日期',
    name: 'moveDt',
    field: 'moveDt',
    align: 'left',
    defOrder: 15,
    sortable: true,
    defVisible: true,
    format: (value: string) => $f.fmt.dtFmtDateOnly(value)
  },
  {
    label: '审核时间',
    name: 'confirmDt',
    field: 'confirmDt',
    align: 'left',
    defOrder: 16,
    defVisible: true,
    format: (value: string) => $f.fmt.dtFmtFullWithMSec(value)
  },
  {
    label: '审核人',
    name: 'confirmPn',
    field: 'confirmPn',
    align: 'left',
    defOrder: 17,
    defVisible: true,
    format: (confirmPn: string, row: WmInvMove) => $f.fmt.userDisp(row.confirmP as string, confirmPn)
  }
]

const $d = reactive({
  tableData: [] as WmInvMove[],
  // 仓库下拉
  whDropdownList: [] as WmWhLite[],
  selectedItems: [] as string[],
  // 货主
  storerDropdownList: [] as MfLite[],
  // 储区下拉
  zoneDropdownList: [] as WmZoneLite[],
  actualFieldShown: {
    expectedDtBegin: {
      isShown: false
    },
    expectedDtEnd: {
      isShown: false
    },
    moveDtBegin: {
      isShown: false
    },
    moveDtEnd: {
      isShown: false
    },
    moveState: {
      isShown: true
    }
  },
  // 过滤项的显示/隐藏配置
  filterOptionList: {
    expectedDtBegin: {
      label: '计划移库日期从',
      show: false,
      order: 1
    },
    expectedDtEnd: {
      label: '计划移库日期至',
      show: false,
      order: 2
    },
    moveDtBegin: {
      label: '实际移库日期从',
      show: false,
      order: 3
    },
    moveDtEnd: {
      label: '实际移库日期至',
      show: false,
      order: 4
    },
    moveState: {
      label: '状态',
      show: true,
      order: 5
    }
  } as Record<string, FilterInfo>,
  moveStateDropdownList: [
    {label: '初始', value: '0'},
    {label: '已审核', value: '1'},
    {label: '移库中', value: '5'},
    {label: '移库完成', value: '9'},
    {label: '已取消', value: 'C'}
  ],

})
let fpsReq: GetInvMoveListReq = reactive({
  moveId: null,
  whId: null,
  storerId: null,
  fZoneId: null,
  tZoneId: null,
  expectedDtBegin: null,
  expectedDtEnd: null,
  moveDtBegin: null,
  moveDtEnd: null,
  moveState: null,
  pageNo: 1,
  pageSize: 40,
  isDescending: false,
  orderBy: null
})
//查询参数日期格式验证
const validators = $f.validators
const rules = {
  expectedDtBegin: {
    date: validators.date
  },
  expectedDtEnd: {
    date: validators.date
  },
  moveDtBegin: {
    date: validators.date
  },
  moveDtEnd: {
    date: validators.date
  }
}
const v$ = useVuelidate(rules, fpsReq, {$autoDirty: true, $scope: false})
const loadListData = function (resetFpsReq?: number) {
  if (resetFpsReq) {
    if (resetFpsReq >= 1) {
      fpsReq.pageNo = 1
    }
    if (resetFpsReq >= 2) {
      fpsReq.orderBy = ''
      fpsReq.isDescending = false
    }
  }
  listDataLoadingState.value = true
  $f.axios.get<GetInvMoveResp>('/wms/inv/inventory/get-inv-move-list', {params: fpsReq})
    .then((result) => {
      result.data.expectedDtBegin = $f.fmt.dtFmtDateOnly(result.data.expectedDtBegin)
      result.data.expectedDtEnd = $f.fmt.dtFmtDateOnly(result.data.expectedDtEnd)
      result.data.moveDtBegin = $f.fmt.dtFmtDateOnly(result.data.moveDtBegin)
      result.data.moveDtEnd = $f.fmt.dtFmtDateOnly(result.data.moveDtEnd)
      $d.selectedItems = []
      fpsAssist.handleGenericFpsResp(result.data)
      $d.tableData = result.data.invMoves
      fpsAssist.saveFpsReq(fpsReq)
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      listDataLoadingState.value = false
    })
}
const {
  fpsInfo,
  fpsAssist,
  fpsNav,
  searchBarVisibility
} = useFpsHelper('/wms/inv/move/',
  '/wms/inv/move/detail',
  '/wms/inv/move/create',
  '/wms/inv/move/edit',
  fpsReq, columnsDefine,
  $d.filterOptionList,
  loadListData)

// 批量删除
const deleteInvMoves = function () {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要删除选中的移库单吗?',
    icon: 'Warning',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/project/mhlbc/inv/inventory/delete-inv-moves', _.map($d.selectedItems, 'moveId'))
        .then(() => {
          $f.ui.closeMsgBox()
          $d.selectedItems = []
          loadListData(2)
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: '删除失败',
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

let showingInvMoveImportDlg = ref(false)
let errorMessageForInvMoveImport = ref('')
let importInvMoveExcelState = ref(false)
let asnListExcelFileInput = ref()
// 批量导入确定
const importInvMoveListExcel = function () {
  importInvMoveExcelState.value = true
  let formData = new window.FormData()
  formData.append('dataFile', asnListExcelFileInput.value.files[0])
  $f.axios
    .post('/project/mhlbc/inv/inventory/import-labeling-moves', formData)
    .then((resp) => {
      showingInvMoveImportDlg.value = false
      $f.ui.showNotifySucceeded('导入成功,已导入数量:' + String(resp.data))
      loadListData(2)
    })
    .catch((err) => {
      if (err.response?.data?.errorList?.length) {
        showingInvMoveImportDlg.value = false
        $f.ui.showErrorListDlg(err.response.data)
      } else {
        errorMessageForInvMoveImport.value = $f.getAxiosErrMsg(err)
      }
    })
    .finally(() => {
      importInvMoveExcelState.value = false
    })
}

// 仓库选择变更
const onWhChanged = function (value: number) {
  fpsReq.fZoneId = null
  fpsReq.tZoneId = null
  void $f.lst.getZoneSimpleList(value)
    .then((resp) => {
      $d.zoneDropdownList = resp.zones
    })
}
// 仓库下拉
void $f.lst.getWmWhSimpleList()
  .then((resp) => {
    $d.whDropdownList = resp
  })
//获取货主下拉数据源
void $f.lst.getMfSimpleList({isStorer: true})
  .then((resp) => {
    $d.storerDropdownList = resp.mfLiteList
  })
// 储区数据源
void $f.lst.getZoneSimpleList(null)
  .then((resp) => {
    $d.zoneDropdownList = resp.zones
  })
const e$ = $f.getFieldErrStr
const fx = $f
</script>
